package com.kerrykidz.filemanagement.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kerrykidz.common.Constants;
import com.kerrykidz.common.PrimaryKeyGenerator;
import com.kerrykidz.common.PrimaryKeyGenerator.BusinessType;
import com.kerrykidz.filemanagement.dao.mapper.LocPerInoutEntityMapper;
import com.kerrykidz.filemanagement.dao.model.HisTicketEntity;
import com.kerrykidz.filemanagement.dao.model.UserInOutCombEntity;
import com.kerrykidz.filemanagement.dao.model.VipUserEntity;
import com.kerrykidz.filemanagement.service.IVipService;
import com.kerrykidz.membership.dao.mapper.CusFngEntityMapper;
import com.kerrykidz.membership.dao.mapper.CusGuaEntityMapper;
import com.kerrykidz.membership.dao.mapper.CusMemClassEntityMapper;
import com.kerrykidz.membership.dao.mapper.CusMemEntityMapper;
import com.kerrykidz.membership.dao.mapper.CusMemHisEntityMapper;
import com.kerrykidz.membership.dao.mapper.CusMemSalesEntityMapper;
import com.kerrykidz.membership.dao.mapper.CusMemSuspendEntityMapper;
import com.kerrykidz.membership.dao.mapper.CusRelEntityMapper;
import com.kerrykidz.membership.dao.model.CusFngEntity;
import com.kerrykidz.membership.dao.model.CusGuaEntity;
import com.kerrykidz.membership.dao.model.CusMemClassEntity;
import com.kerrykidz.membership.dao.model.CusMemEntity;
import com.kerrykidz.membership.dao.model.CusMemSalesEntity;
import com.kerrykidz.membership.dao.model.CusMemSuspendEntity;
import com.kerrykidz.membership.dao.model.CusRelEntity;
import com.kerrykidz.sales.dao.model.PosOrderEntity;
import com.kerrykidz.sales.dao.model.PosOrderPrdEntity;
import com.kerrykidz.sales.service.IOrderService;
import com.kerrykidz.scminvoicing.dao.model.GblScmPrdEntity;
import com.kerrykidz.system.util.UserUtil;
import com.kerrykidz.system.vo.UserInfo;
import com.rdp.framework.core.model.MyBatisSuperModel;
import com.rdp.framework.exception.RDPException;
import com.rdp.util.GenerationUUID;

/**
 * 会员管理服务接口
 * @author YJJ
 */
@Service
public class VipServiceImpl implements IVipService {

	private Logger loger = LoggerFactory.getLogger(VipServiceImpl.class);

	@Autowired
	private CusMemHisEntityMapper cusMemHisEntityMapper;
	@Autowired
	private CusMemEntityMapper cusMemEntityMapper;
	@Autowired
	private LocPerInoutEntityMapper locPerInoutEntityMapper;
	@Autowired
	private CusGuaEntityMapper cusGuaEntityMapper;
	@Autowired
	private CusRelEntityMapper cusRelEntityMapper;
	@Autowired
	private  CusMemSalesEntityMapper salesMapper;
	@Autowired
	private CusFngEntityMapper fngMapper;
	@Autowired
	private CusMemSuspendEntityMapper cusMemSuspendEntityMapper;
	@Autowired
	IOrderService orderService;
	@Autowired
	private CusMemClassEntityMapper cusMemClassEntityMapper;

	@Override
	public List<VipUserEntity> listVipUser(MyBatisSuperModel model) {
		String queryType = (String) model.getParams().get(Constants.MEMBER_QUERY_TYPE);
		if("2".equals(queryType)){
			//列表分页
			model.setIspaging(true);
		}
		return cusMemHisEntityMapper.listVipUser(model);
	}

	@Override
	public void updateVip(CusMemEntity memberDetail) throws RDPException {

		// 判断会员是否选中
		if(memberDetail.getIsVip()!=null && memberDetail.getIsVip().equals("on")){
			memberDetail.setIsVip("1");
		}else{
			memberDetail.setIsVip("0");
		}

		// 判断消费余额是否选中
		if(memberDetail.getCanConsume()!=null && memberDetail.getCanConsume().equals("on")){
			memberDetail.setCanConsume("1");
		}else{
			memberDetail.setCanConsume("0");
		}

		// 判断单独游玩免责声明已签署是否选中
		if(memberDetail.getSignDisclaimer()!=null && memberDetail.getSignDisclaimer().equals("on")){
			memberDetail.setSignDisclaimer("1");
		}else{
			memberDetail.setSignDisclaimer("0");
		}
		
		//更新会员信息??缺少指纹
		cusMemEntityMapper.updateEntity(memberDetail);
		
		// 更换销售
		if (StringUtils.isNotBlank(memberDetail.getFkSales())) {
			CusMemSalesEntity entity = new CusMemSalesEntity();
			entity.setFkMemId(memberDetail.getPkMemId());
			entity.setFkSales(memberDetail.getFkSales());
			entity.setModiBy(memberDetail.getModiBy());
			List<CusMemSalesEntity> list = salesMapper.findSaleByMemberId(entity);
			if (list.size() == 0) {
				salesMapper.saveEntity(entity);
			} else {
				salesMapper.updateSalesByMemberId(entity);
			}
		}
		
		// 更换指纹
		if (StringUtils.isNotBlank(memberDetail.getFing1()) || StringUtils.isNotBlank(memberDetail.getFing2())) {
			CusFngEntity fng = new CusFngEntity();
			fng.setFing1(memberDetail.getFing1());
			fng.setFing2(memberDetail.getFing2());
			fng.setFtype1(memberDetail.getFtype1());
			fng.setFtype2(memberDetail.getFtype2());
			fng.setFkMemId(memberDetail.getPkMemId());
			fng.setFkBranId(memberDetail.getFkBranId());
			List<CusFngEntity> fngList = fngMapper.findFingerprintByPerson(fng);
			if (fngList.size() > 0) {
				fngMapper.updateEntity(fng);
			} else {
				fng.setPkFingId(GenerationUUID.getGenerationUUID());
				fngMapper.saveEntity(fng);
			}
		}
		
	}

	/**
	 * 获取会员进出场纪录
	 */
	@Override
	public List<UserInOutCombEntity> listVipInOutHis(List<String> memberIdList) {
		return locPerInoutEntityMapper.listVipInOutHis(memberIdList);
	}
	
	/**
	 * 获取会员购票历史纪录
	 */
	@Override
	public List<HisTicketEntity> getBuyTicketHisList(List<String> memberIdList) {
		return cusMemHisEntityMapper.getBuyTicketHisList(memberIdList);
	}

	/**
	 * 创建会员
	 */
	@Override
	public void createVip(CusMemEntity memberDetail) throws RDPException {
		// 判断会员是否选中
		if(memberDetail.getIsVip()!=null && memberDetail.getIsVip().equals("on")){
			memberDetail.setIsVip("1");
		}else{
			memberDetail.setIsVip("0");
		}

		// 判断消费余额是否选中
		if(memberDetail.getCanConsume()!=null && memberDetail.getCanConsume().equals("on")){
			memberDetail.setCanConsume("1");
		}else{
			memberDetail.setCanConsume("0");
		}

		// 判断单独游玩免责声明已签署是否选中
		if(memberDetail.getSignDisclaimer()!=null && memberDetail.getSignDisclaimer().equals("on")){
			memberDetail.setSignDisclaimer("1");
		}else{
			memberDetail.setSignDisclaimer("0");
		}
		// 获取生成的会员Id
		UserInfo user = UserUtil.getUserFromSession();
		String pkMemId = PrimaryKeyGenerator.getPrimaryKey(BusinessType.HY, user.getAbbrCode());

		// 设置会员属性
		memberDetail.setPkMemId(pkMemId);
		//memberDetail.setMemType("1");//标识为会员
		//创建会员??缺少会员头像和指纹
		cusMemEntityMapper.saveEntity(memberDetail);
		
		// 添加销售
		if (StringUtils.isNotBlank(memberDetail.getFkSales())) {
			CusMemSalesEntity entity = new CusMemSalesEntity();
			entity.setFkMemId(memberDetail.getPkMemId());
			entity.setActiveFlag("0");
			entity.setFkSales(memberDetail.getFkSales());
			entity.setFkBranId(memberDetail.getFkBranId());
			entity.setModiBy(memberDetail.getModiBy());
			salesMapper.saveEntity(entity);
		}
		
		// 添加指纹
		if (StringUtils.isNotBlank(memberDetail.getFing1()) || StringUtils.isNotBlank(memberDetail.getFing2())) {
			CusFngEntity fng = new CusFngEntity();
			fng.setFing1(memberDetail.getFing1());
			fng.setFing2(memberDetail.getFing2());
			fng.setFtype1(memberDetail.getFtype1());
			fng.setFtype2(memberDetail.getFtype2());
			fng.setFkMemId(memberDetail.getPkMemId());
			fng.setFkBranId(memberDetail.getFkBranId());
			
			List<CusFngEntity> fngList = fngMapper.findFingerprintByPerson(fng);
			if (fngList.size() > 0) {
				fngMapper.updateEntity(fng);
			} else {
				fng.setPkFingId(GenerationUUID.getGenerationUUID());
				fngMapper.saveEntity(fng);
			}
		}
		
	}

	/**
	 * 创建监护人
	 * @throws Exception 
	 */
	@Override
	public void createGuardian(CusGuaEntity cuardian) throws RDPException {
		loger.debug("createGuardian()begin");
		
		// 更新会员变更人、时间
		CusMemEntity member = new CusMemEntity();
		member.setPkMemId(cuardian.getMemberId());
		member.setModiBy(cuardian.getModiBy());
		cusMemEntityMapper.updateEntity(member);
		
		//获取监护人Id
		String pkGuaId=GenerationUUID.getGenerationUUID();

		//设置监护人属性
		cuardian.setPkGuaId(pkGuaId);

		// 判断消费余额是否选中
		if(cuardian.getCanConsume()!=null && cuardian.getCanConsume().equals("on")){
			cuardian.setCanConsume("1");
		}else{
			cuardian.setCanConsume("0");
		}

		// 判断可接领是否选中
		if(cuardian.getCanReceive()!=null && cuardian.getCanReceive().equals("on")){
			cuardian.setCanReceive("1");
		} else {
			cuardian.setCanReceive("0");
		}

		// 暂时将分店编号设置为：WX
		//cuardian.setFkBranId("WX");

		// 保存监护人信息到表[CUS_GUA]
		cusGuaEntityMapper.saveEntity(cuardian);

		//！！！[CUS_REL]表中FK_RELTYPE_ID（目前关系类型编号页面写死）&&FK_SIBLINGS_ID

		// 保存家庭成员关系到表[CUS_REL]
		CusRelEntity cusRelEntity=new CusRelEntity();
		cusRelEntity.setFkGuaId(pkGuaId);
		cusRelEntity.setFkMemId(cuardian.getMemberId());
		cusRelEntity.setFkReltypeId(cuardian.getFkReltypeId());
		cusRelEntityMapper.saveEntity(cusRelEntity);

		// 更换指纹
		if (StringUtils.isNotBlank(cuardian.getFing1()) || StringUtils.isNotBlank(cuardian.getFing2())) {
			CusFngEntity fng = new CusFngEntity();
			fng.setFing1(cuardian.getFing1());
			fng.setFing2(cuardian.getFing2());
			fng.setFtype1(cuardian.getFtype1());
			fng.setFtype2(cuardian.getFtype2());
			fng.setFkGuaId(cuardian.getPkGuaId());
			fng.setFkBranId(cuardian.getFkBranId());
			List<CusFngEntity> fngList = fngMapper.findFingerprintByPerson(fng);
			if (fngList.size() > 0) {
				fngMapper.updateEntity(fng);
			} else {
				fng.setPkFingId(GenerationUUID.getGenerationUUID());
				fngMapper.saveEntity(fng);
			}
		}
		loger.debug("createGuardian()end");
	}

	/**
	 * 编辑监护人
	 */
	@Override
	public void updateGuardian(CusGuaEntity cuardian) throws RDPException {
		
		// 更新会员变更人、时间
		CusMemEntity member = new CusMemEntity();
		member.setPkMemId(cuardian.getMemberId());
		member.setModiBy(cuardian.getModiBy());
		cusMemEntityMapper.updateEntity(member);
		
		// 判断消费余额是否选中
		if(cuardian.getCanConsume()!=null && cuardian.getCanConsume().equals("on")){
			cuardian.setCanConsume("1");
		}else{
			cuardian.setCanConsume("0");
		}

		// 判断可接领是否选中
		if(cuardian.getCanReceive()!=null && cuardian.getCanReceive().equals("on")){
			cuardian.setCanReceive("1");
		}else{
			cuardian.setCanReceive("0");
		}
		cusGuaEntityMapper.updateEntity(cuardian);
		

		// 保存家庭成员关系到表[CUS_REL]
		CusRelEntity cusRelEntity=new CusRelEntity();
		cusRelEntity.setFkGuaId(cuardian.getPkGuaId());
		cusRelEntity.setFkMemId(cuardian.getMemberId());
		cusRelEntity.setFkReltypeId(cuardian.getFkReltypeId());
		cusRelEntityMapper.updateEntity(cusRelEntity);

		// 更换指纹
		if (StringUtils.isNotBlank(cuardian.getFing1()) || StringUtils.isNotBlank(cuardian.getFing2())) {
			CusFngEntity fng = new CusFngEntity();
			fng.setFing1(cuardian.getFing1());
			fng.setFing2(cuardian.getFing2());
			fng.setFtype1(cuardian.getFtype1());
			fng.setFtype2(cuardian.getFtype2());
			fng.setFkGuaId(cuardian.getPkGuaId());
			fng.setFkBranId(cuardian.getFkBranId());
			List<CusFngEntity> fngList = fngMapper.findFingerprintByPerson(fng);
			if (fngList.size() > 0) {
				fngMapper.updateEntity(fng);
			} else {
				fng.setPkFingId(GenerationUUID.getGenerationUUID());
				fngMapper.saveEntity(fng);
			}
		}
	}

	public CusGuaEntity getGuaByMemberIdAndGuaId(String memberId, String guaId)
			throws RDPException {
		return cusGuaEntityMapper.getGuaByMemberIdAndGuaId(memberId, guaId);
	}

	public List<VipUserEntity> findMemberByTelOrEmail(MyBatisSuperModel model) {
		String queryType = (String) model.getParams().get(Constants.MEMBER_QUERY_TYPE);
		if("2".equals(queryType)){
			//列表分页
			model.setIspaging(true);
		}
		List<VipUserEntity> list = cusMemHisEntityMapper.findMemberByTelOrEmail(model);
		
	/*	//异常情况，号码查询时空值依然有一条数据
		if(null!=list && list.size()==1){
			if(list.get(0).getPkMemId()==null || list.get(0).getPkMemId().equals("")){
				list=null;
			}
		}*/
		return list;
	}

	/**
	 * 根据会员ID查询会员所购会籍商品
	 * 
	 * @param pkMemId
	 * @return
	 * @throws RDPException
	 */
	public GblScmPrdEntity getPrdByMemberId(@Param("pkMemId") String pkMemId) {
		return cusMemHisEntityMapper.getPrdByMemberId(pkMemId);
	}

	public String createNotPayOfOrder(PosOrderEntity order, List<PosOrderPrdEntity> products, UserInfo user, List<CusMemClassEntity> cusMemClassList) throws Exception {
		String orderId = orderService.createNotPayOfOrder(order, products, user.getAbbrCode());
		//加上购买课程历史记录
		if(null!=cusMemClassList && cusMemClassList.size()>0){
			for (int i = 0; i < cusMemClassList.size(); i++) {
				CusMemClassEntity cusMemClass=cusMemClassList.get(i);
				cusMemClass.setFkOrderId(orderId);
				cusMemClassEntityMapper.saveEntity(cusMemClass);
			}
		}
		return orderId;
	}
	
	/**
	 * 根据停卡ID查询会员会员停卡记录(唯一)
	 * 
	 * @param memberId
	 *            会员编号
	 * @return
	 */
	public CusMemSuspendEntity getUniSuspendByMemberId(@Param("memberId") String memberId){
		return cusMemSuspendEntityMapper.getUniSuspendByMemberId(memberId);
	}

	/**
	 * 根据批次号查询进场数量
	 */
	public Integer findCountByFambatch(String famBatch) throws RDPException {
		return locPerInoutEntityMapper.findCountByFambatch(famBatch);
	}
	
	/**
	 * 查询订单明细的成人票数量
	 * @param pkOrderId:订单Id
	 * @return
	 */
	public Integer getTicketCount(@Param("pkOrderId") String pkOrderId){
		return cusMemHisEntityMapper.getTicketCount(pkOrderId);
	}
	
	/**
	 * 查询订单明细的成人票数量
	 * @param pkOrderId:订单Id
	 * @return
	 */
	public Integer getTicketCountContainone(@Param("pkOrderId") String pkOrderId){
		return cusMemHisEntityMapper.getTicketCountContainone(pkOrderId);
	}

}
